package cn.itcast.blog.Utils;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
 * 因为factory是单实例的，可以被单独拿出来，进行优化
 * 单例就要去保证安全
 * @author 16604
 *
 */
public class SessionFactoryUtils {
	
	//至始至终，在内存只有一份
	public static SqlSessionFactory sqlSessionFactory;
	
	public static SqlSessionFactory getFactory() {
		
		if(sqlSessionFactory == null) {
			
			//用类当锁
			synchronized (SessionFactoryUtils.class) {
				
				if(sqlSessionFactory == null) {
					
					//factory只会被初始化一次
					try {
						sqlSessionFactory = 
								new SqlSessionFactoryBuilder().build(
										Resources.getResourceAsStream("mybatis.xml"));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}
		return sqlSessionFactory;
	}
}
